package com.qfedu.stussm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.stussm.dao.JclassDao;
import com.qfedu.stussm.dto.JclassDto;
import com.qfedu.stussm.entity.Classes;
import com.qfedu.stussm.entity.Jclass;
import com.qfedu.stussm.service.intf.JclassService;
import com.qfedu.stussm.vo.PageBeanVo;
import com.qfedu.stussm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Service
public class JclassServiceImpl implements JclassService {
    @Autowired
    private JclassDao dao;
    @Override
    public R add(Jclass jclass) {
        if (dao.add(jclass) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public PageBeanVo selectAll(String name, int page, int limit) {
        //1.开启分页
        PageHelper.startPage(page, limit);
        if (name != null) {
            name = "%" + name + "%";
        }
        //2.获取查询的结果
        PageInfo<JclassDto> pageInfo=new PageInfo<>(dao.select(name));
        //3.返回结果
        return new PageBeanVo(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public R delete(Integer id) {
        if (dao.delete(id) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R update(JclassDto jclass) {
        if (dao.update(jclass) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public void createExcel(HttpServletResponse response) throws IOException {
        //1.查询数据
        List<JclassDto> list=dao.selectAll();
        //2.设置文件下载
        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename=department_"+System.currentTimeMillis()+".xlsx");
        //3.生成Excel并写出
        EasyExcel.write(response.getOutputStream(),JclassDto.class).sheet(System.currentTimeMillis()+"").doWrite(list);
    }

    @Override
    public R delMany(Integer[] ids) {
        if (dao.delMany(ids) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }
}
